﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Data;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Flow;
using Think9.Services.Table;

namespace Think9.Controllers.Basic
{
    [Area("SysTable")]
    public class TbRelationController : BaseController
    {
        private ComService ComService = new ComService();
        private TbBasicService TbServer = new TbBasicService();
        private TbIndexService TbIndex = new TbIndexService();
        private TbRelationService TbRelationService = new TbRelationService();
        private RelationRDService RelationRDService = new RelationRDService();
        private RelationRDFieldService RelationRDFieldService = new RelationRDFieldService();
        private RelationListService RelationListService = new RelationListService();
        private RelationWDService RelationWDService = new RelationWDService();

        public ActionResult List(string tbid)
        {
            ViewBag.tbid = tbid;
            return View();
        }

        public ActionResult BeforeAdd(string tbid)
        {
            string err = TbRelationService.BeforeAdd(tbid);

            if (string.IsNullOrEmpty(err))
            {
                return Json(SuccessTip(""));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        [HttpGet]
        public ActionResult EditR2(string tbid, int id)
        {
            ViewBag.tbid = tbid;
            ViewBag.id = id;

            string maintbid = GetTbID.GetMainTbId(tbid);
            //可选择的数据源绑定
            DataTable dt = TbServer.GetMainAndGridTb(maintbid);
            ViewBag.FromTbList = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            //目标字段的绑定
            dt = TbIndex.GetSelectFieldListByTbId(tbid);
            ViewBag.FillIndexId = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            RelationRDEntity model = new RelationRDEntity();
            if (id == 0)
            {
                ViewBag.Guid = Think9.Services.Basic.CreatCode.NewGuid();
                model.RelationName = "数据初始化";
                model.FromTbId = "-1";
                model.ICount = "3";
                model.RelationType = "21";
                model.TbID = tbid;
                model.OrderType = "2";
            }
            else
            {
                ViewBag.Guid = "";
                RelationListEntity mList = RelationListService.GetByWhereFirst("where RelationId=" + id + "");
                if (mList == null)
                {
                    model = null;
                }
                else
                {
                    if (mList.ICount == -1)
                    {
                        model = RelationRDService.GetByWhereFirst("where RelationId=" + id + "");

                        model.ICount = "-1";
                        model.RelationName = mList.RelationName;
                        model.RelationType = "21";
                        model.TbID = tbid;
                    }
                    else
                    {
                        model.ICount = mList.ICount.ToString();
                        model.FromTbId = "-1";
                        model.RelationName = mList.RelationName;
                        model.RelationType = "21";
                        model.TbID = tbid;
                        model.OrderType = "1";
                    }
                }
            }

            if (model == null)
            {
                return Json("数据不存在");
            }
            else
            {
                return View(model);
            }
        }

        [HttpPost]
        public ActionResult EditR2(string guid, int id, string tbid, RelationRDEntity model)
        {
            string err = "";
            int rid = 0;

            if (id == 0)
            {
                if (model.FromTbId == "-1" && string.IsNullOrEmpty(model.ICount))
                {
                    err = "请输入空值行数";
                }

                if (string.IsNullOrEmpty(err))
                {
                    err = TbRelationService.AddRelationRead(ref rid, "21", int.Parse(model.ICount), guid, tbid, model);
                }
            }
            else
            {
                err = TbRelationService.EditRelationRead(id, model);
            }

            if (string.IsNullOrEmpty(err))
            {
                return Json(SuccessTip("保存成功"));
            }
            else
            {
                if (rid != 0)
                {
                    TbRelationService.Delete(rid.ToString());
                }
                return Json(ErrorTip(err));
            }
        }

        [HttpGet]
        public ActionResult EditR1(string tbid, int id)
        {
            ViewBag.tbid = tbid;
            ViewBag.id = id;
            ViewBag.Guid = "";

            string maintbid = GetTbID.GetMainTbId(tbid);
            //可选择的数据源绑定
            DataTable dt = TbServer.GetMainAndGridTb(maintbid);
            ViewBag.FromTbList = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            //目标字段的绑定
            dt = TbIndex.GetSelectFieldListByTbId(tbid);
            ViewBag.FillIndexId = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            RelationRDEntity model = RelationRDService.GetByWhereFirst("where RelationId=" + id + "");

            if (model == null)
            {
                return Json("数据不存在");
            }
            else
            {
                ViewBag.fid = model.FromTbId;
                RelationListEntity model2 = RelationListService.GetByWhereFirst("where RelationId=" + id + "");

                model.RelationName = model2 == null ? "" : model2.RelationName;
                model.ICount = model2 == null ? "" : model2.ICount.ToString();
                model.RelationType = "11";
                model.TbID = tbid;
                model.FromTbName = GetTbID.GetTbName(model.FromTbId);
                return View(model);
            }
        }

        [HttpPost]
        public ActionResult EditR1(int id, string tbid, RelationRDEntity model)
        {
            string err = "";

            try
            {
                err = TbRelationService.EditRelationRead(id, model);
            }
            catch (Exception ex)
            {
                err = ex.Message;
            }

            if (string.IsNullOrEmpty(err))
            {
                return Json(SuccessTip("编辑成功"));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        [HttpGet]
        public ActionResult AddR1(string tbid)
        {
            ViewBag.Guid = Think9.Services.Basic.CreatCode.NewGuid();
            ViewBag.tbid = tbid;
            ViewBag.id = 0;

            string maintbid = GetTbID.GetMainTbId(tbid);

            //可选择的数据源绑定
            DataTable dt = TbServer.GetMainAndGridTb(maintbid);
            ViewBag.FromTbList = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            //目标字段的绑定
            dt = TbIndex.GetSelectFieldListByTbId(tbid);
            ViewBag.FillIndexId = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            return View();
        }

        [HttpPost]
        public ActionResult AddR1(string guid, string tbid, RelationRDEntity model)
        {
            string err = "";
            int rid = 0;

            try
            {
                if (ComService.GetTotal("sys_temp", "where Guid='" + guid + "'") == 0)
                {
                    err = "至少添加一条读取字段";
                }

                if (string.IsNullOrEmpty(err))
                {
                    err = TbRelationService.AddRelationRead(ref rid, "11", -1, guid, tbid, model);
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
            }

            if (string.IsNullOrEmpty(err))
            {
                return Json(SuccessTip("添加成功"));
            }
            else
            {
                if (rid != 0)
                {
                    TbRelationService.Delete(rid.ToString());
                }

                return Json(ErrorTip(err));
            }
        }

        [HttpGet]
        public ActionResult AddR3(string tbid)
        {
            FlowService FlowService = new FlowService();
            DataTable dt;

            ViewBag.Guid = Think9.Services.Basic.CreatCode.NewGuid();
            ViewBag.tbid = tbid;
            ViewBag.id = 0;

            string maintbid = GetTbID.GetMainTbId(tbid);

            //适用范围
            dt = FlowService.GetFlowListForTbRelation(maintbid);
            ViewBag.FlowList = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            //回写数据表
            dt = TbServer.GetMainAndGridTb(maintbid);
            ViewBag.FromTbList = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            return View();
        }

        [HttpPost]
        public ActionResult AddR3(string guid, string tbid, RelationWriteEntity model)
        {
            string err = "";
            int rid = 0;

            try
            {
                if (ComService.GetTotal("sys_temp", "where Guid='" + guid + "'") == 0)
                {
                    err += "至少添加一条回写字段";
                }

                if (string.IsNullOrEmpty(model.FlowPrcs) || model.FlowPrcs.Replace("#", "").Trim() == "")
                {
                    err += "请选择适用范围";
                }

                if (string.IsNullOrEmpty(err))
                {
                    err = TbRelationService.AddRelationWrite(ref rid, "31", guid, tbid, model);
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
            }

            if (string.IsNullOrEmpty(err))
            {
                return Json(SuccessTip("添加成功"));
            }
            else
            {
                if (rid != 0)
                {
                    TbRelationService.Delete(rid.ToString());
                }

                return Json(ErrorTip(err));
            }
        }

        [HttpGet]
        public ActionResult EditR3(string tbid, int id)
        {
            ViewBag.tbid = tbid;
            ViewBag.id = id;
            ViewBag.Guid = "";

            FlowService FlowService = new FlowService();
            string maintbid = GetTbID.GetMainTbId(tbid);

            //适用范围
            DataTable dt = FlowService.GetFlowListForTbRelation(maintbid);
            ViewBag.FlowList = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            //回写数据表
            dt = TbServer.GetMainAndGridTb(maintbid);
            ViewBag.FromTbList = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            RelationWriteEntity model = RelationWDService.GetByWhereFirst("where RelationId=" + id + "");

            if (model == null)
            {
                return Json("数据不存在");
            }
            else
            {
                model.FlowPrcs_Exa = model.FlowPrcs;
                ViewBag.fid = model.WriteTbId;
                RelationListEntity model2 = RelationListService.GetByWhereFirst("where RelationId=" + id + "");

                model.RelationName = model2 == null ? "" : model2.RelationName;
                model.RelationType = "31";
                model.TbID = tbid;
                model.FromTbName = GetTbID.GetTbName(model.WriteTbId);
                return View(model);
            }
        }

        [HttpPost]
        public ActionResult EditR3(int id, string tbid, RelationWriteEntity model)
        {
            string err = "";

            try
            {
                err = TbRelationService.EditRelationWrite(id, model);
            }
            catch (Exception ex)
            {
                err = ex.Message;
            }

            if (string.IsNullOrEmpty(err))
            {
                return Json(SuccessTip("编辑成功"));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        [HttpGet]
        public ActionResult PUFormula(string tbid, string fid, string some)
        {
            ViewBag.tbid = tbid;
            ViewBag.formid = fid;
            ViewBag.some = some;

            //可选择的数据源绑定
            DataTable dt = TbServer.GetMainAndGridTb();
            ViewBag.FromTbList = DataTableHelp.ToEnumerable<valueTextEntity>(dt);

            return View();
        }

        public ActionResult SelectValue(string tbid)
        {
            ViewBag.tbid = tbid;
            return View();
        }

        [HttpGet]
        public ActionResult GetIndexAndParameterList(string tbid)
        {
            var result = new { code = 0, msg = "", count = 999999, data = DataTableHelp.ToEnumerable<valueTextEntity>(TbIndex.GetIndexAndParameterList(tbid)) };

            return Json(result);
        }

        [HttpGet]
        public JsonResult GetMainAndGridTbIndexList(string id)
        {
            string _Id = id == null ? "" : id;
            return Json(DataTableHelp.ToEnumerable<valueTextEntity>(TbIndex.GetMainAndGridTbIndexList(_Id)));
        }

        [HttpGet]
        public JsonResult GetSelectValueFieldByTb(string id)
        {
            string _Id = id == null ? "" : id;
            return Json(DataTableHelp.ToEnumerable<valueTextEntity>(TbIndex.GetSelectFieldListByTbId(_Id)));
        }

        [HttpGet]
        public JsonResult GetSelectOrderFieldByTbId(string id)
        {
            string _Id = id == null ? "" : id;
            return Json(DataTableHelp.ToEnumerable<valueTextEntity>(TbIndex.GetSelectOrderListByTbId(_Id)));
        }

        [HttpGet]
        public JsonResult GetConditionFieldList(string id)
        {
            string _Id = id == null ? "" : id;
            return Json(DataTableHelp.ToEnumerable<valueTextEntity>(TbIndex.GetConditionFieldList01(_Id)));
        }

        [HttpGet]
        public JsonResult GetList(RelationListEntity model, PageInfoEntity pageInfo, string tbid)
        {
            long total = 0;
            pageInfo.field = "TbRelation.RelationId";

            var list = RelationListService.GetPageList(ref total, model, pageInfo, tbid);
            var result = new { code = 0, msg = "", count = total, data = list };
            return Json(result);
        }

        [HttpPost]
        public ActionResult AddListFiled(string guid, string id, string value, string value2)
        {
            string err = "";
            try
            {
                if (string.IsNullOrEmpty(guid))
                {
                    err = TbRelationService.AddListFiled(id, value, value2);
                }
                else
                {
                    err = TbRelationService.AddListFiledTemp(guid, value, value2);
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
            }

            if (err == "")
            {
                return Json(SuccessTip("添加成功"));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        [HttpPost]
        public ActionResult AddListFiled2(string guid, string id, string value, string value2)
        {
            string err = "";
            try
            {
                if (string.IsNullOrEmpty(guid))
                {
                    err = TbRelationService.AddListFiled2(id, value, value2);
                }
                else
                {
                    err = TbRelationService.AddListFiledTemp2(guid, value, value2);
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
            }

            if (err == "")
            {
                return Json(SuccessTip("添加成功"));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        [HttpPost]
        public ActionResult GetListFiled(string guid, string id, string tbid, string fromtbid)
        {
            fromtbid = fromtbid == null ? "" : fromtbid;
            if (string.IsNullOrEmpty(guid))
            {
                var result = new { code = 0, msg = "", count = 999999, data = TbRelationService.GetListFiledRead(id, tbid, fromtbid) };

                return Json(result);
            }
            else
            {
                var result = new { code = 0, msg = "", count = 999999, data = TbRelationService.GetListFiledTemp(guid, tbid, fromtbid) };

                return Json(result);
            }
        }

        [HttpPost]
        public ActionResult GetListFiled2(string guid, string id, string writetbid)
        {
            writetbid = writetbid == null ? "" : writetbid;
            if (string.IsNullOrEmpty(guid))
            {
                var result = new { code = 0, msg = "", count = 999999, data = TbRelationService.GetListFiledWrite(id, writetbid) };

                return Json(result);
            }
            else
            {
                var result = new { code = 0, msg = "", count = 999999, data = TbRelationService.GetListFiledTemp2(guid, writetbid) };

                return Json(result);
            }
        }

        [HttpGet]
        public ActionResult DeleteFiled(string id, string guid)
        {
            string err = "";
            if (string.IsNullOrEmpty(guid))
            {
                err = RelationRDFieldService.DeleteByWhere("where id=" + id + "") ? "" : "删除失败";
            }
            else
            {
                err = TbRelationService.DelListFiledTemp(id);
            }

            if (err == "")
            {
                return Json(SuccessTip(""));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        [HttpGet]
        public ActionResult Delete(string id)
        {
            string err = TbRelationService.Delete(id);

            if (err == "")
            {
                return Json(SuccessTip("删除成功"));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        [HttpGet]
        public ActionResult GetSelectIndexList(string tbid)
        {
            tbid = tbid == null ? "" : tbid;
            var result = new { code = 0, msg = "", count = 999999, data = TbIndex.GetIndexByTbID2(GetTbID.GetTbIdByFlowTbId(tbid)) };

            return Json(result);
        }
    }
}